package com.shi.shiro.config;

import com.shi.shiro.filter.LoginCheckFilter;
import com.shi.shiro.shiro.CustomerRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.config.ShiroFilterConfiguration;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.servlet.Filter;
import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {


    @Resource
    private LoginCheckFilter loginCheckFilter;

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        filterFactoryBean.setSecurityManager(securityManager);
        Map<String, Filter> filters = new LinkedHashMap<>();
        // 添加自定义过滤器
        filters.put("loginCheck",loginCheckFilter);
        filterFactoryBean.setFilters(filters);

        // 添加拦截的资源map
        Map<String, String> chainDefinitionMap = new LinkedHashMap<>();
        chainDefinitionMap.put("/**","loginCheck");
        filterFactoryBean.setFilterChainDefinitionMap(chainDefinitionMap);

        // 解决自定义过滤器执行两次的问题
        ShiroFilterConfiguration shiroFilterConfiguration = new ShiroFilterConfiguration();
        shiroFilterConfiguration.setFilterOncePerRequest(true);
        filterFactoryBean.setShiroFilterConfiguration(shiroFilterConfiguration);
        return filterFactoryBean;
    }

    @Bean
    public DefaultWebSecurityManager securityManager(Realm realm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm);
        return securityManager;
    }


    @Bean
    public Realm realm(){
        CustomerRealm customerRealm = new CustomerRealm();
        HashedCredentialsMatcher md5 = new HashedCredentialsMatcher("MD5");
        customerRealm.setCredentialsMatcher(md5);
        return customerRealm;
    }
}
